import { defineStore } from 'pinia'
import { getConfig } from '@/api/app'
import cache from '@/utils/cache'
import { LANGUAGE } from '@/enums/cacheEnums'
import { Languages } from '@/types/languages'
import { onLaunch } from '@dcloudio/uni-app'
import { getImg } from '@/utils/util'
interface AppSate {
    config: Record<string, any>
    language: Languages
    tabbarCurrent: number
}

export const useAppStore = defineStore({
    id: 'appStore',
    state: (): AppSate => ({
        config: {
            tabbar: []
        },
        language: cache.getLanguage(),
        tabbarCurrent: 0
    }),
    getters: {
        getWebsiteConfig: (state) => state.config.website || {},
        getLoginConfig: (state) => state.config.login || {},
        getTabbarConfig: (state) => state.config.tabbar || [],
        getStyleConfig: (state) => state.config.style || {},
        getH5Config: (state) => state.config.h5 || {}
    },
    actions: {
        getImageUrl(url: string) {
            const { VITE_APP_BASE_URL } = import.meta.env
            if (url && url.startsWith('http')) {
                return url
            }
            // Otherwise, append VITE_APP_BASE_URL to the url
            return `${VITE_APP_BASE_URL}/api${url}`
        },
        async getConfig() {
            const { data, ok } = await getConfig()
            if (!ok) return

            this.config = data
        },
        // 切换语言
        toggleLanguage(val: Languages, isOnLaunch = false) {
            // { text: '中文', value: 'zh-cn', iconfont: 'icon-fuhao-zhongwen' },
            cache.set(LANGUAGE, val)
            this.language = val

            // 不为启动时才设置语言
            if (!isOnLaunch) {
                uni.setLocale(val.value)
            }
        }
    }
})
